import { useEffect, useMemo, useState, useCallback } from 'react';
import { Card, Form, Row, Col, Input, Button, Table, Empty, Pagination, App, Modal, Steps, Alert } from 'antd';
import { findShopList, delBind } from '../../services/login';
type RowType = {
  key: string;
  shopId: string;
  shopName: string;
  platform: string;
  createTime: string;
  id?: string; // 用于解绑
};

export default function ShopList() {
  const { message } = App.useApp();
  const [shopId, setShopId] = useState('');
  const [title, setTitle] = useState('');
  const [data, setData] = useState<RowType[]>([]);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [addShopVisible, setAddShopVisible] = useState<boolean>(false);
  const [douyinAuthVisible, setDouyinAuthVisible] = useState<boolean>(false);
  const [kuaishouAuthVisible, setKuaishouAuthVisible] = useState<boolean>(false);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const res = await findShopList({ id: shopId, shopName: title, pageNum, pageSize });
      console.log("🚀 ~ refresh ~ res:", res)
      const body = res?.result?.body || res?.body || res;
      if (body?.code === 200) {
        const list = Array.isArray(body.data) ? body.data : [];
        setData(list.map((it: unknown, idx: number) => {
          const item = it as Record<string, unknown>;
          return { 
            key: String(item.shopId || idx), 
            shopId: String(item.shopId || ''),
            shopName: String(item.shopName || ''),
            platform: String(item.platform || ''),
            createTime: String(item.createTime || ''),
            id: item.id
          };
        }));
        setTotal(Number(body.totalCount || 0));
      }
    } catch (e) {
      console.warn('findShopList failed:', e);
    } finally {
      setLoading(false);
    }
  }, [shopId, title, pageNum, pageSize]);

  const handleUnbind = useCallback(async (row: RowType) => {
    try {
      // 二次确认弹窗
      Modal.confirm({
        title: '解绑店铺',
        content: '确定要解绑店铺吗？',
        onOk: async () => {
          const res = await delBind({ userId: row.id, id: row.shopId, platform: row.platform });
          console.log("🚀 ~ onOk ~ res:", res)
          if (res?.result?.body?.code === 200) {
            message.success('解绑成功');
            refresh();
          }
        }
      });
    } catch (e) {
      console.warn('delBind failed:', e);
    }
  }, [message, refresh]);

  const handleAddShop = (platform: string) => {
    console.log('添加店铺平台:', platform);
    setAddShopVisible(false);
    // 根据平台打开对应的授权弹窗
    if (platform === 'douyin') {
      setDouyinAuthVisible(true);
    } else if (platform === 'kuaishou') {
      setKuaishouAuthVisible(true);
    }
  };

  // 抖音授权相关函数
  const handleDouyinBuyService = () => {
    window.open("https://fuwu.jinritemai.com/detail?service_id=23297");
  };

  const handleDouyinAuthorize = () => {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
    const userId = userInfo.userId || 'unknown';
    window.open(
      `https://fuwu.jinritemai.com/authorize?service_id=23297&state=fx_${userId}`
    );
    Modal.confirm({
      title: '提示',
      content: '是否授权成功?',
      onOk: () => {
        refresh();
        setDouyinAuthVisible(false);
      },
      onCancel: () => {}
    });
  };

  // 快手授权相关函数
  const handleKuaishouBuyService = () => {
    window.open("https://fuwu.kwaixiaodian.com/new/detail?id=21310148548146");
  };

  const handleKuaishouAuthorize = () => {
    const userInfo = JSON.parse(localStorage.getItem('user') || '{}');
    const userId = userInfo.userId || 'unknown';
    window.open(
      `https://open.kwaixiaodian.com/oauth/authorize?app_id=ks689895171327135709&redirect_uri=https%3A%2F%2Fkwai.jiayia.com%2F%23%2Fdflogin&scope=merchant_refund,merchant_item,merchant_order,user_info,merchant_dropshipping,merchant_item_basic,merchant_servicemarket,merchant_user,merchant_comment,merchant_logistics&response_type=code&state=fx_${userId}`
    );
    Modal.confirm({
      title: '提示',
      content: '是否授权成功?',
      onOk: () => {
        refresh();
        setKuaishouAuthVisible(false);
      },
      onCancel: () => {}
    });
  };

  const columns = useMemo(() => [
    { title: '店铺ID', dataIndex: 'shopId', key: 'shopId', width: '20%' },
    { title: '店铺名称', dataIndex: 'shopName', key: 'shopName', width: '20%' },
    {
      title: '所属平台', dataIndex: 'platform', key: 'platform', width: '20%',
      render: (v: string) => { return v === 'douyin' ? '抖音' : '快手' }
    },
    { title: '绑定时间', dataIndex: 'createTime', key: 'createTime', width: '20%' },
    {
      title: '操作', key: 'action', width: '20%',
      render: (_: unknown, row: RowType) => <Button danger onClick={() => handleUnbind(row)}>解绑</Button>
    },
  ], [handleUnbind]);


  useEffect(() => {
    refresh();
  }, [refresh]);

  return (
    <div className="shop-list-page">
      <Card style={{ marginBottom: 8 }}>
        <Form layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item label="店铺Id">
                <Input placeholder="请输入店铺ID" value={shopId} onChange={(e) => setShopId(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="店铺名称">
                <Input placeholder="请输入店铺名称" value={title} onChange={(e) => setTitle(e.target.value)} />
              </Form.Item>
            </Col>
            <Col span={8} style={{ display: 'flex', alignItems: 'flex-end' }}>
              <Form.Item>
                <Button type="primary" onClick={() => { setPageNum(1); refresh(); }}>查询</Button>
                <Button style={{ marginLeft: 8 }} type="primary" onClick={() => setAddShopVisible(true)}>添加店铺</Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card>
        <Table
          dataSource={data}
          columns={columns}
          pagination={false}
          loading={loading}
          locale={{ emptyText: <Empty description="暂无数据" /> }}
          scroll={{ y: 480 }}
          rowKey="key"
        />
        <div style={{ marginTop: 8, textAlign: 'right' }}>
          <Pagination
            size="small"
            showSizeChanger
            pageSizeOptions={[20, 50, 100, 200]}
            current={pageNum}
            pageSize={pageSize}
            total={total}
            onChange={(p) => setPageNum(p)}
            onShowSizeChange={(_, s) => setPageSize(s)}
          />
        </div>
      </Card>

      {/* 添加店铺弹窗 */}
      <Modal
        title="添加店铺"
        open={addShopVisible}
        onCancel={() => setAddShopVisible(false)}
        footer={null}
        width={500}
      >
        <div style={{ display: 'flex', justifyContent: 'space-around', alignItems: 'center', padding: '20px 0' }}>
          {/* 抖音 */}
          <div
            style={{
              width: 180,
              height: 180,
              border: '1px solid #ececec',
              borderRadius: 5,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <div
              style={{
                width: '100%',
                height: '50%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <img src='' style={{ width: 60, height: 60 }} alt="抖音" />
            </div>
            <div style={{ border: '1px solid #ececec', width: '80%', margin: '10px 0' }}></div>
            <div
              style={{
                width: '100%',
                height: '49%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Button 
                type="primary"
                onClick={() => handleAddShop('douyin')}
              >
                添加抖音
              </Button>
            </div>
          </div>

          {/* 快手 */}
          <div
            style={{
              width: 180,
              height: 180,
              border: '1px solid #ececec',
              borderRadius: 5,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <div
              style={{
                width: '100%',
                height: '50%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <img src='' style={{ width: 60, height: 60 }} alt="快手" />
            </div>
            <div style={{ border: '1px solid #ececec', width: '80%', margin: '10px 0' }}></div>
            <div
              style={{
                width: '100%',
                height: '49%',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Button 
                type="primary"
                onClick={() => handleAddShop('kuaishou')}
              >
                添加快手
              </Button>
            </div>
          </div>
        </div>
      </Modal>

      {/* 抖音授权弹窗 */}
      <Modal
        title="抖音店铺授权"
        open={douyinAuthVisible}
        onCancel={() => setDouyinAuthVisible(false)}
        footer={null}
        width="70%"
      >
        <div className="add-shop-pc">
          {/* 提示信息 */}
          <Alert
            message={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ marginRight: 16 }}>
                  <img
                    src=""
                    alt=""
                    style={{ width: 50, height: 15 }}
                  />
                </div>
                <div>
                  <div>需订购[灵猴分销铺货]，订购[灵猴一键下单]订单回流</div>
                  <div style={{ marginTop: 6 }}>
                    灵猴分销铺货订购费低至0元/月，灵猴一键下单(免费试用7天)15元/月
                  </div>
                </div>
              </div>
            }
            type="warning"
            style={{ marginBottom: 15 }}
          />

          {/* 授权步骤 */}
          <Steps
            direction="vertical"
            items={[
              {
                title: (
                  <div style={{ lineHeight: '30px' }}>
                    <div>步骤一</div>
                    <div style={{ color: '#31373d' }}>
                      订购【灵猴分销铺货】 + 抖音【灵猴一键下单】获取订单回流权限
                    </div>
                    <div style={{ color: '#999' }}>
                      需前往抖店服务市场订购【灵猴一键下单】
                    </div>
                    <div>
                      <Button 
                        type="primary" 
                        size="small" 
                        onClick={handleDouyinBuyService}
                        style={{ marginRight: 8 }}
                      >
                        立即订购
                      </Button>
                      <Button 
                        size="small" 
                        onClick={handleDouyinAuthorize}
                      >
                        已订购去授权
                      </Button>
                    </div>
                  </div>
                ),
              },
              {
                title: (
                  <div style={{ lineHeight: '30px' }}>
                    <div>步骤二</div>
                    <div style={{ color: '#31373d' }}>授权成功，开始下单</div>
                    <div style={{ color: '#999' }}>提示授权成功后返回软件，即可操作</div>
                  </div>
                ),
              },
            ]}
          />
        </div>
      </Modal>

      {/* 快手授权弹窗 */}
      <Modal
        title="快手店铺授权"
        open={kuaishouAuthVisible}
        onCancel={() => setKuaishouAuthVisible(false)}
        footer={null}
        width="70%"
      >
        <div className="add-shop-pc">
          {/* 提示信息 */}
          <Alert
            message={
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ marginRight: 16 }}>
                  <img
                    src=""
                    alt=""
                    style={{ width: 50, height: 15 }}
                  />
                </div>
                <div>
                  <div>需订购[灵猴分销铺货]，订购[灵猴采购代发]订单回流</div>
                  <div style={{ marginTop: 6 }}>
                    灵猴分销铺货订购费低至0元/月，灵猴采购代发(免费试用7天)20元/月
                  </div>
                </div>
              </div>
            }
            type="warning"
            style={{ marginBottom: 15 }}
          />

          {/* 授权步骤 */}
          <Steps
            direction="vertical"
            items={[
              {
                title: (
                  <div style={{ lineHeight: '30px' }}>
                    <div>步骤一</div>
                    <div style={{ color: '#31373d' }}>
                      订购【灵猴分销铺货】 + 快手【灵猴采购代发】获取订单回流权限
                    </div>
                    <div style={{ color: '#999' }}>
                      需前往快手服务市场订购【灵猴采购代发】
                    </div>
                    <div>
                      <Button 
                        type="primary" 
                        size="small" 
                        onClick={handleKuaishouBuyService}
                        style={{ marginRight: 8 }}
                      >
                        立即订购
                      </Button>
                      <Button 
                        size="small" 
                        onClick={handleKuaishouAuthorize}
                      >
                        已订购去授权
                      </Button>
                    </div>
                  </div>
                ),
              },
              {
                title: (
                  <div style={{ lineHeight: '30px' }}>
                    <div>步骤二</div>
                    <div style={{ color: '#31373d' }}>授权成功，开始下单</div>
                    <div style={{ color: '#999' }}>提示授权成功后返回软件，即可操作</div>
                  </div>
                ),
              },
            ]}
          />
        </div>
      </Modal>
    </div>
  );
}


